import { useEffect, useRef } from 'react'
import audioPlayer from '@/lib/music/audioPlayer'

const canvasWidth = 1500
const canvasHeight = 200
/**
 * 音频可视化
 * @returns
 */
export default function MusicVisualization() {
  //   const [spectrum, setSpctrum] = useState(new Uint8Array())
  const canvasRef = useRef<HTMLCanvasElement>(null)
  useEffect(() => {
    let isend = false
    const ctx = canvasRef.current?.getContext('2d')
    const update = () => {
      if (isend) return
      if (!ctx) return
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      const array = audioPlayer.getByteFrequencyData()
      for (let i = 0; i < array.length; i++) {
        if (array[i] === 0) continue
        const percentage = array[i] / 256
        ctx.fillStyle = `hsl(${i * 2}, 100%, 50%)`
        ctx.fillRect(i * 7, canvasHeight, 5, -canvasHeight * percentage)
      }
      requestAnimationFrame(update)
    }
    update()
    return () => {
      isend = true
    }
  }, [])
  return (
    <div style={{ display: 'flex' }}>
      <canvas
        ref={canvasRef}
        width={canvasWidth}
        height={canvasHeight}
        style={{
          borderRadius: '5px',
          border: '1px solid #ccc',
          padding: '3px',
          width: '100%',
        }}></canvas>
    </div>
  )
}
